package com.audience.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("server is running...");
        for (;;){
            Socket socket=serverSocket.accept();
            System.out.println("connected from "+socket.getRemoteSocketAddress());
            Thread thread=new Handler(socket);
            thread.start();
        }
    }
}

class Handler extends Thread{
    Socket socket;

    public Handler(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        try (InputStream inputStream = socket.getInputStream()) {
            try (OutputStream outputStream = socket.getOutputStream()) {
                handle(inputStream,outputStream);
            }
        } catch (IOException e) {
            try {
                this.socket.close();
            } catch (IOException ioException) {
            }
            System.out.print("client disconnected.");
        }
    }

    private void handle(InputStream inputStream,OutputStream outputStream) throws IOException {
        var write = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
        var reader = new BufferedReader(new InputStreamReader(inputStream,StandardCharsets.UTF_8));
        write.write("hello\n");
        write.flush();
        for (;;){
            String s=reader.readLine();
            if (s.equals("bye")){
                write.write("bye\n");
                write.flush();
                break;
            }
            write.write("ok: "+s+"\n");
            write.flush();
        }
    }
}
